<template>
  <div>
    <h1>图书分类管理</h1>
    <!-- 新增分类表单 -->
    <el-form :model="newCategory" label-width="80px">
      <el-form-item label="分类名称">
        <el-input v-model="newCategory.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="addCategory">新增分类</el-button>
      </el-form-item>
    </el-form>
    <!-- 分类列表 -->
    <el-table :data="categories" stripe>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="name" label="分类名称"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="mini" @click="editCategory(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteCategory(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑分类对话框 -->
    <el-dialog :visible.sync="editDialogVisible" title="编辑分类">
      <el-form :model="editCategoryData" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="editCategoryData.name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEditedCategory">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';

// 模拟分类数据
const categories = ref([
  { id: 1, name: '文学' },
  { id: 2, name: '历史' },
  { id: 3, name: '科学' }
]);

// 新增分类表单数据
const newCategory = ref({ name: '' });

// 编辑分类对话框相关数据
const editDialogVisible = ref(false);
const editCategoryData = ref({ id: null, name: '' });

// 新增分类方法
const addCategory = () => {
  if (newCategory.value.name) {
    const newId = categories.value.length > 0 ? categories.value[categories.value.length - 1].id + 1 : 1;
    categories.value.push({ id: newId, name: newCategory.value.name });
    newCategory.value.name = '';
  }
};

// 编辑分类方法
const editCategory = (category) => {
  editCategoryData.value = { ...category };
  editDialogVisible.value = true;
};

// 保存编辑后的分类方法
const saveEditedCategory = () => {
  const index = categories.value.findIndex(item => item.id === editCategoryData.value.id);
  if (index !== -1) {
    categories.value[index] = { ...editCategoryData.value };
    editDialogVisible.value = false;
  }
};

// 删除分类方法
const deleteCategory = (id) => {
  const index = categories.value.findIndex(item => item.id === id);
  if (index !== -1) {
    categories.value.splice(index, 1);
  }
};
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>
